<template>
    <view class="page_main">
        <HeaderBar title="精品路线"></HeaderBar>
        <view class="info">
            <view class="title">{{ merchantInfo.name}}</view>
            <view class="text">{{merchantInfo.memo}}</view>
            <view class="tags">
                <view class="tag" v-for="(item,index) in merchantInfo.tags" :key="index">{{ item }}</view> 
            </view>  
        </view>
        <view class="form_c">
            <view class="num">
                <view class="n_text">数量</view>
                <wd-input-number v-model="numValue" :min="1" @change="handleNumChange" />  
            </view>
            <view class="people_n" @click="togglePopup">
                出行人：
                <view class="people_l" v-show="adultNum">{{ adultNum }}成人</view>
                <view class="people_l" v-show="childrenNum">{{ childrenNum }}儿童</view>
            </view>
            <view class="count">
                <view class="people_c">需选{{ peopleCount }}位游客</view>
                <view class="tips">
                    请务必保证填写项与出游所持证件一致
                </view> 
                <view class="people_list">
                    <view class="p_item" :class="item.selected?'active':''" v-for="(item,index) in touristInfoList" :key="index" @click="handSelected(item)">{{ item.name }}</view> 
                    <view class="p_item" @click="addTourist">选择/新增</view>
                </view>
                <view class="input_list">
                    <view class="input_item" v-for="(item,index) in information" :key="index">
                        <view class="input">
                            <view class="input_i">
                                姓名：{{ item.name }}
                            </view>
                            <view class="input_i">
                                身份证号：{{ item.idCard }}
                            </view>
                        </view> 
                        <wd-icon name="chevron-right" size="22px"></wd-icon>     
                    </view> 
                </view>
                <view class="contact">
                    联系方式
                </view>
                <view class="notes">
                    <view class="title">备注信息</view>
                    <wd-textarea v-model="notes" placeholder="请输入备注信息" />  
                </view>
                <view class="radios">
                    <label class="radio"><radio class="radio_c" :value="agree" :checked="agree" @click="changeCheck('agree')" />请阅读井同意以下内容</label>
				    <label class="radio"><radio class="radio_c" :value="guide" :checked="guide" @click="changeCheck('guide')" /><view>预订须知与<text>高海拔提示</text>以及<text>合同条款</text>，<text>高龄人群/孕妇出行声明</text></view></label>
                </view>    
            </view>
        </view>
        <view class="btns">
            <view class="price">
                ￥{{ totalPrice }}
            </view>
            <view class="btn_l">
                <view class="btn_p">
                    <!-- 明细 -->
                    <wd-drop-menu direction="up">
                        <wd-drop-menu-item title="明细" @change="handleChange" >
                            <view class="detail_main">
                                <view class="title">金额明细</view>
                                <view class="detail_content">
                                    <view class="d_item">
                                        <view>套餐费</view> 
                                        <wd-divider dashed></wd-divider>
                                        <view>￥{{ totalPrice }}</view> 
                                    </view>
                                    <view class="d_item">
                                        <view>成人</view> 
                                        <view><text>￥{{ orderInfo.adultPrice }}</text><text>×{{adultNum}}人</text></view> 
                                    </view>
                                    <view class="d_item">
                                        <view>儿童</view> 
                                        <view><text>￥{{ orderInfo.childrenPrice }}</text><text>×{{childrenNum}}人</text></view>
                                    </view>
                                </view>  
                            </view> 
                        </wd-drop-menu-item>
                    </wd-drop-menu>
                </view>
                <button class="btn" :class="{ 'selected': isPayButtonEnabled }" 
                :disabled="!isPayButtonEnabled"  @click="handGoPay">去支付</button>
                <!-- <button class="btn" @click="handGoPay">去支付</button> -->
            </view>   
        </view>
        <wd-popup v-model="popupShow" position="bottom" closable custom-style="height: 280px;" @close="handleClose">
            <view class="label">选择人数</view>
            <view class="cell">
                <view class="txt">
                    <view>成人<text class="t">12周岁及以上</text></view>
                </view>
                <wd-input-number v-model="tempAdultNum" :min="0" @change="handleAdultNumChange" />  
            </view>
            <view class="cell">
                <view class="txt">
                    <view>儿童<text class="t">2~12周岁（不含12周岁）</text></view>
                </view>
                <wd-input-number v-model="tempChildrenNum":min="0" @change="handleChildNumChange" />  
            </view>
            <button class="btn_c" @click="confirmPeople">确认人数</button>    
        </wd-popup>
        <AddTourist 
        :showAddTourist="showAddTourist"
        :touristInfoList="touristInfoList"
        @close="handleCloseAddTourist"
        @queryTouristList="queryTouristList(false)"
        ></AddTourist>   
    </view>
</template>

<script lang="ts" setup>
import HeaderBar from "@/components/HeaderBar/index.vue";
import { addOrder} from "@/premiumRouteSubPack/api/index";
import {toPay, touristList} from "@/api/common";
import {onLoad} from "@dcloudio/uni-app";
import AddTourist from "@/components/AddTourist/index.vue";
import { ref, computed } from 'vue';

// const tags =ref(['4A级','免费停车','含导游'])
const numValue = ref<number>(1)
const adultNum = ref(0)  //成人数量
const childrenNum = ref(0)      //儿童数量
const peopleCount = computed(() => adultNum.value + childrenNum.value);      //总人数
// const selected = ref(false)  //是否选择出行人
const popupShow = ref(false)        //展示popup
const notes = ref('')       //备注信息
const agree = ref(false)       //阅读并同意
const guide = ref(false)       //须知
const checked = ref(false)       //已选中
const merchantInfo = ref({})     //商户信息
const orderInfo = ref({})        // 已选套餐、出行日期信息
const totalPrice = ref<number>(0);      // 总价格
const couponDiscount = ref<number>(0);      // 优惠券折扣
const tempAdultNum = ref(0); // 临时成人数量
const tempChildrenNum = ref(0); // 临时儿童数量
//人员列表
const touristInfoList = ref([
    // {name:'张三',idCard:'510606198207250648',phoneNum:'15846666548',idCardType:'1',type:'0',selected:false},
    // {name:'李四',idCard:'510606198207250648',phoneNum:'15846666548',idCardType:'1',type:'0',selected:false},
    // {name:'王五',idCard:'510606198207250648',phoneNum:'15846666548',idCardType:'1',type:'1',selected:false},
])
const information = ref([])   //已选中出行人列表
const showAddTourist = ref(false);
// const choiceProduct = ref({});

onLoad((options)=>{
    const dataString = decodeURIComponent(options.merchantInfo);
    merchantInfo.value = JSON.parse(dataString);
    orderInfo.value = uni.getStorageSync('orderInfo');  
    //thaliName 套餐名称、thaliId套餐Id、adultPrice成人价、childrenPrice儿童价、date出行日期
    console.log('套餐信息',orderInfo.value.thaliId);
    // tempAdultNum.value = adultNum.value; // 初始化临时成人数量
    // tempChildrenNum.value = childrenNum.value; // 初始化临时儿童数量
    tempAdultNum.value = orderInfo.value.adultNumVal; // 初始化弹窗成人数量
    tempChildrenNum.value = orderInfo.value.childrenNumVal; // 初始化弹窗儿童数量
    adultNum.value = orderInfo.value.adultNumVal; // 初始化临时成人数量
    childrenNum.value = orderInfo.value.childrenNumVal; // 初始化临时儿童数量
    popupShow.value = !(orderInfo.value.adultNumVal || orderInfo.value.childrenNumVal);  // 根据套餐判读是否可编辑人数
    calculateTotalPrice();
})
onShow(async() => {
    await queryTouristList(true);
});
//获取出行人列表
const queryTouristList = async (isShowLoad) => {
    await touristList({pageSize:99,userId:2}).then(res => {
      let {result} = res;
      if(result && result.length > 0) {
        touristInfoList.value = result.map((item) => ({
            ...item,
            selected: false
        }));
      }
        //   touristInfoList.value = res;
        //   console.log('isShowLoad',isShowLoad);
        //   idCardValidate();
        information.value = []
    });
  };
//选择出行人
const handSelected =(e)=>{
    const index = touristInfoList.value.findIndex((info) => info.name === e.name);
    if (index !== -1) {
        // 如果找到了，切换 selected 属性
        touristInfoList.value[index].selected = !touristInfoList.value[index].selected;

        // 根据 selected 属性决定是否添加到 information 列表
        if (touristInfoList.value[index].selected) {
        // 如果选中，添加到 information 列表
        information.value.push({
            name: e.name,
            idCardType: e.idType , // 如果没有 idCardType 属性，给一个默认值
            idCard: e.idCard ,  // 身份证号，
            phoneNum: e.tel  , // 电话
            type: e.yn  , // 0成人，1儿童
        });
        } else {
            // 如果未选中，从 information 列表移除
            const infoIndex = information.value.findIndex((info) => info.name === e.name);
            if (infoIndex !== -1) {
                information.value.splice(infoIndex, 1);
            }
        }
    }
}
//数量变化
const handleNumChange = ({ value }) => {
    numValue.value = value;
    adultNum.value = Math.round(tempAdultNum.value * value);
    childrenNum.value = Math.round(tempChildrenNum.value * value);
    calculateTotalPrice();
    console.log('计数', value);
};

// 处理成人数量变化
const handleAdultNumChange = ({ value }) => {
    tempAdultNum.value = value;
};

// 处理儿童数量变化
const handleChildNumChange = ({ value }) => {
    tempChildrenNum.value = value;
};

// 确认人数
const confirmPeople = () => {
    adultNum.value = Math.round(tempAdultNum.value * numValue.value);
    childrenNum.value = Math.round(tempChildrenNum.value * numValue.value);
    calculateTotalPrice();
    popupShow.value = false;
};
//查看明细
const handleChange =()=>{
    console.log('展开明细');
    
}
//展开人员数量选择弹窗
const togglePopup = () => {
    if (orderInfo.value.adultNumVal > 0 || orderInfo.value.childrenNumVal > 0) {
        popupShow.value = false;
    } else {
        popupShow.value = true;
    }
};
//关闭人员数量弹窗
const handleClose =()=>{
    popupShow.value = false
}


//新增/选择出行人
const addTourist =()=>{
    console.log('222');
    showAddTourist.value = true
}
//关闭新增/选择弹窗
const handleCloseAddTourist=()=>{
    showAddTourist.value = false
}

const changeCheck =(e)=>{
    switch (e) {
        case 'agree':
            agree.value = !agree.value
        break;
        case 'guide':
            guide.value = !guide.value
        break;
    }
}
const calculateTotalPrice = () => {
  totalPrice.value = Number(
    (adultNum.value * orderInfo.value.adultPrice + 
     childrenNum.value * orderInfo.value.childrenPrice - 
     couponDiscount.value
    ).toFixed(2)
  );
};
const handGoPay =()=>{
    const parmas = ref({
        useDate: orderInfo.value.date, // 出行日期
        source: 1, // 来源，根据业务需求设置
        totalAmount: totalPrice.value, // 总金额
        payAmount: totalPrice.value, // 支付金额，这里假设支付金额等于总金额
        discountAmount: couponDiscount.value, // 折扣金额
        memo: notes.value, // 备注信息
        adultNum: adultNum.value, // 成人数量
        childrenNum: childrenNum.value, // 儿童数量
        thaliId: orderInfo.value.thaliId, // 套餐ID
        buyNum: numValue.value, // 购买数量
        travelers: information.value.map(item => ({
            name: item.name, // 游客姓名
            idCard: item.idCard, // 游客身份证号
            idCardType: item.idCardType, // 身份证类型
            phoneNum: item.phoneNum, // 游客电话
            type: item.type // 游客类型，0成人，1儿童
        }))
    });
    addOrder(parmas.value).then((res)=>{
        console.log('res-------',res);
        let {result} = res;
        handleToPay(result)
    })
}
const handleToPay = async (id) => {
    await toPay({type:"jsapi",id:id.orderId}).then(res => {
      let { appId,nonceStr, packageValue,paySign,signType,timeStamp } = res.result;
      console.log('.......res',res);
      uni.navigateTo({
        url:`/ticketSubPack/pages/PaymentOrder/index?totalPrice=${totalPrice.value}&timeStamp=${timeStamp}&nonceStr=${nonceStr}&packageValue=${encodeURIComponent(packageValue)}&signType=${signType}&paySign=${encodeURIComponent(paySign)}&orderId=${id}`
      })
    });
  };
  // 判断按钮是否可用
const isPayButtonEnabled = computed(() => {
    return information.value.length === peopleCount.value && agree.value && guide.value;
});
</script>

<style lang="scss" scoped>
.page_main{
    background: #eeefe7;
    // height: 100vh;
    padding-bottom: 200rpx;
    position: relative;
    .info{
        background: #fff;
        padding:50rpx 25rpx 40rpx;
        .title{
            font-size: 39rpx;
        }
        .text{
            margin: 37rpx 0 41rpx;
        }
        .tags{
            display: flex;
            align-items: center;
            .tag{
                font-size: 22rpx;
                padding: 10rpx 15rpx;
                background: #EEEFE7;
                border:1rpx solid #1b9c61;
                margin-right: 20rpx;
            }
        }
    }
    .form_c{
        margin:30rpx 28rpx 45rpx;
        background: #fff;
        border-radius: 10rpx;
        padding: 40rpx 28rpx;
        .num{
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-bottom: 20rpx;
            border-bottom: 1rpx solid #C0C2B3;
            .n_text{
                font-size: 30rpx;
                font-weight: bold;
            }
        }
        .people_n{
            display: flex;
            align-items: center;
            font-size: 29rpx;
            font-weight: bold;
            padding: 36rpx 0 30rpx;
            .people_l{}
        }
        .count{
            .people_c{
                font-size: 29rpx;
                font-weight: bold;
            }
            .tips{
                margin-top: 10rpx;
                color: #777777;
            }
            .people_list{
                margin-top: 32rpx;
                display: flex;
                align-items: center;
                flex-wrap: wrap;
                .p_item{
                    width: 174rpx;
                    height: 60rpx;
                    border: 1rpx solid #1b9c61;
                    border-radius: 10rpx;
                    line-height: 60rpx;
                    text-align: center;
                    margin-right: 28rpx;
                    margin-top: 20rpx;
                    &:nth-child(3n){
                        margin-right: 0;
                    }
                    &:nth-child(-n+3){
                        margin-top: 0rpx;
                    }
                }
                .active{
                    color: #fff;
                    background: #1b9c61;
                }
            }
            .input_list{
                margin-top: 20rpx;
                .input_item{
                    display: flex;
                    align-content: center;
                    justify-content: space-between;
                    padding: 20rpx 0;
                    border-bottom: 1rpx solid #C0C2B3;
                    .input{
                        .input_i{
                            margin-top: 20rpx;
                        }
                    }
                    :deep(.wd-icon){
                        display: flex;
                        align-items: center;
                    }
                }
            }
            .contact{
                margin-top: 34rpx;
                padding: 20rpx;
                border-radius: 10rpx;
                background: #EEEFE7;
            }
            .notes{
                margin-top: 34rpx;
                border-radius: 10rpx;
                border: 1px solid #C0C2B3;
                .title{
                    padding: 20rpx;
                    font-weight: bold;
                }
            }
            .radios{
                display: flex;
                flex-direction: column;
                margin-top: 35rpx;
                color: #777;
                font-size: 25rpx;
                .radio{
                    margin-top: 15rpx;
                    display: flex;
                    justify-content: flex-start;
                    .radio_c{
                    }
                }
                text{
                    color: #f88a41;
                }
            }
        }
    }
    .btns{
        background: #fdffe8;
        position: absolute;
        bottom: 0;
        left: 0;
        width: calc(100% - 120rpx);
        height: 120rpx;
        padding: 0 60rpx;
        padding-bottom: env(safe-area-inset-bottom);
        display: flex;
        align-items: center;
        justify-content: space-between;
        .price{
            color: #AA5413 ;
            font-size: 42rpx;
            font-weight: bold;
        }
        .btn_l{
            display: flex;
            align-items: center;
            .btn_p{
                :deep(.wd-drop-menu__list){
                    background: transparent;
                    .wd-drop-menu__item-title{
                        font-size: 29rpx;
                    }
                }
                :deep(.is-active) {
                    ::after {
                        display: none;
                    }
                }
            }
            .btn{
                width: 163rpx;
                height: 83rpx;
                border-radius: 10rpx;
                margin-left: 20rpx;
                background: #C0C2B3 ;
                color: #a7a7a7;
                padding: 0;
                display: flex;
                align-items: center;
                justify-content:center
            }
            .selected{
                color: #fff;
                background: #AA5414;
            }
        }
    }
    .label{
        padding: 30rpx 20rpx 50rpx;
        text-align: center;
        background: linear-gradient(180deg, #a2e0b7, #fff);
        border-radius: 10rpx 10rpx 0 0;
    }
    .cell{
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 30rpx 0 ;
        border-bottom: 1rpx solid #ebece6;
        margin: 0rpx 30rpx;
    }
    .btn_c{
        width: 636rpx;
        height: 70rpx;
        margin: 40rpx auto 0;
        background: #1b9c61;
        border-radius: 10rpx;
        color: #fff;
        line-height: 70rpx;
    }
    .detail_main{
        padding: 30rpx;
        .title{
            text-align: center;
            font-weight: bold;
        }
        .detail_content{
            margin-top: 20rpx;
            .d_item{
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 30rpx;
                text{
                    margin-left: 20rpx;
                }
                :deep(.wd-divider){
                    flex:1;
                }
            }
        }
    }
}
</style>